package pl.edu.pb.wi.cookbook.interceptor;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import pl.edu.pb.wi.cookbook.entity.User;
import pl.edu.pb.wi.cookbook.service.UserService;
import pl.edu.pb.wi.cookbook.session.UserSession;
import pl.edu.pb.wi.cookbook.util.HashUtil;

public class AdminInterceptor extends HandlerInterceptorAdapter {
    private static final String ADMIN_LOGIN = "admin";
    private static final String ADMIN_PASSWORD = "admin";
    private static final String ADMIN_EMAIL = "admin@admin.pl";

    private UserSession userSession;
    private UserService userService;

    @Autowired
    public AdminInterceptor(UserSession userSession, UserService userService) {
        this.userSession = userSession;
        this.userService = userService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
        if (!userSession.getIsAdmin()) {
            User admin = userService.getUserByLogin(ADMIN_LOGIN);
            if (admin == null) {
                admin = new User();
                admin.setLogin(ADMIN_LOGIN);
                admin.setPassword(HashUtil.hashInput(ADMIN_PASSWORD));
                admin.setEmail(ADMIN_EMAIL);
                admin.setCreatedAt(new Date());
                admin.setLastLoginAt(new Date());
                admin.setAdmin(true);
                admin.setValidationHash(String.format("%s%s",
                        HashUtil.hashInput(ADMIN_LOGIN),
                        HashUtil.hashInput(ADMIN_EMAIL)));
                admin.setValidated(true);
                userService.addUser(admin);
            }

            response.sendRedirect(request.getContextPath() + "/main");
            return false;
        } else {
            return super.preHandle(request, response, handler);
        }
    }
}
